package site.marqstree.latte.ec.sign;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import site.marqstree.latte.ec.db.DatabaseManager;
import site.marqstree.latte.ec.db.UserProfile;
import site.marqstree.latte.core.app.AccountManager;

/*
 * 项目名: EleCommerce
 * 包名: site.marqstree.latte.ec.sign
 * 文件名: SignHandler
 * 创建者: marqstree
 * 创建时间: 2020/1/19 14:56
 * 描述: TODO
 */
public class SignHandler {

    //登陆成功后
    // 1)记录用户信息到Sqlite
    // 2)记录登陆成功状态到sp
    // 3)执行登陆回调
    public static void onSignIn(String response, ISignListener signListener) {
        //解析登陆返回json
        final JSONObject profileJson = JSON.parseObject(response).getJSONObject("data");
        final long userId = profileJson.getLong("userId");
        final String name = profileJson.getString("name");
        final String avatar = profileJson.getString("avatar");
        final String gender = profileJson.getString("gender");
        final String address = profileJson.getString("address");
        //将用户信息存入Sqlite
        final UserProfile profile = new UserProfile(userId, name, avatar, gender, address);
        DatabaseManager.getInstance().getDao().insert(profile);
        //记录已登陆状态到sp
        AccountManager.setSignState(true);
        //调用登陆成功回调
        signListener.onSignInSuccess();
    }

    //注册成功后
    // 1)记录用户信息到Sqlite
    // 2)记录注册成功标识到Sqlite
    // 3)执行注册成功回调
    public static void onSignUp(String response, ISignListener signListener) {
        final JSONObject profileJson = JSON.parseObject(response).getJSONObject("data");
        final long userId = profileJson.getLong("userId");
        final String name = profileJson.getString("name");
        final String avatar = profileJson.getString("avatar");
        final String gender = profileJson.getString("gender");
        final String address = profileJson.getString("address");

        final UserProfile profile = new UserProfile(userId, name, avatar, gender, address);
        DatabaseManager.getInstance().getDao().insert(profile);

        //记录已登陆成功状态到sp
        AccountManager.setSignState(true);
        //执行注册成功回调
        signListener.onSignUpSuccess();
    }
}